<!--
 * @Author: liaoxing
 * @Date: 2022-01-14 11:53:24
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-23 18:19:14
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\business\quote\params\collapsItem\index.vue
-->
<template>
  <el-form
    :model="itemData"
    :style="{width: formData.parameterType != 'ASSEMBLE' ? '600px' : '900px'}"
    :rules="formData.parameterType != 'ASSEMBLE' ? rules : rules2"
    :ref="'formData' + formIndex"
    label-width="130px"
    class="demo-ruleForm"
  >
    <el-form-item label="所属分类" prop="folderId">
      <div class="absolute" style="z-index: 99" v-if="categoryList.length">
        <chooseTree
          :treeList="categoryList"
          :defaultProps="{children: 'children', label: 'title'}"
          :nodeKey="'key'"
          @getResult="getFolderId"
          :initId="itemData.folderId"
        ></chooseTree>
      </div>
    </el-form-item>
    <el-form-item label="参数名称" prop="parameterName">
      <el-input :disabled="itemData.parameterType == 'BOT'" v-model="itemData.parameterName"></el-input>
    </el-form-item>
    <!-- <el-form-item label="参数类型" prop="parameterType">
      <el-select :disabled="itemData.parameterType == 'BOT'" v-model="itemData.parameterType" placeholder="请选择参数类型">
        <el-option v-for="(item, index) in parameterTypeList" :key="'parameterTypeList' + index" :label="item.name" :value="item.value"></el-option>
      </el-select>
    </el-form-item>-->
    <!-- <el-form-item label="" v-if="itemData.parameterType">
      <parameterTypeModule :type="itemData.parameterType"></parameterTypeModule>
    </el-form-item>-->
    <!-- <el-form-item label="参数处理器" v-if="itemData.parameterType && itemData.parameterType != 'INPUT'">
      <el-input v-model="itemData.preHandler"></el-input>
    </el-form-item>-->
    <template v-if="formData.parameterType != 'ASSEMBLE'">
      <el-form-item label="数据来源" prop="parameterValueFrom">
        <el-select
          :disabled="itemData.parameterType == 'BOT'"
          v-model="itemData.parameterValueFrom"
          placeholder="请选择数据来源"
          @change="changeParameterValueFrom"
        >
          <el-option
            v-for="(item, index) in parameterValueFromList"
            :key="'parameterValueFromList' + index"
            :label="item.name"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="系统处理器" v-if="itemData.parameterValueFrom && itemData.parameterValueFrom == 'BOT'">
        <el-input v-model="itemData.postHandler"></el-input>
      </el-form-item>-->

      <el-form-item
        label="数据维护者"
        v-if="itemData.parameterValueFrom != 'BOT' && itemData.parameterValueFrom"
      >
        <!-- <el-input v-model="itemData.parameterValueMaintainer"></el-input> -->
        <div class="absolute" style="z-index: 98">
          <template v-if="itemData.parameterValueFrom == 'USER' && personList.length">
            <div @click="openSelectMember = !openSelectMember" class="selectInput">{{ selectMemberName }}</div>
            <selectMember v-if="openSelectMember" class="selectBox" key="user" ref="selectMember" :selectMemberList.sync="selectMemberList" :showPhone="true" :showConfirm="false"  @getSelectMemberList="getSelectMemberList" :multiple="false"
            ></selectMember>
          </template>
          <!--             
            v-if="itemData.parameterValueFrom == 'USER' && personList.length"
            :initId.sync="itemData.parameterValueMaintainer"
            :treeList.sync="personList"
            :defaultProps.sync="userProps"
            @getResult="getUserId" 
          -->

          <chooseTree
            key="role"
            v-if="itemData.parameterValueFrom == 'ROLE' && roleList.length"
            :initId.sync="itemData.parameterValueMaintainer"
            :treeList.sync="roleList"
            :defaultProps.sync="roleProps"
            @getResult="getRoleId"
          ></chooseTree>
        </div>
      </el-form-item>

      <!-- <el-form-item label="数据有效期" prop="durationType">
        <el-radio-group :disabled="itemData.parameterType == 'BOT'" v-model="itemData.durationType">
          <el-radio :label="0">一次性</el-radio>
          <el-radio :label="1">区间性</el-radio>
        </el-radio-group>
      </el-form-item>-->

      <!-- <el-form-item label="参数值" prop="parameterValue">
        <el-input v-model="itemData.parameterValue"></el-input>
      </el-form-item>

      <el-form-item label="有效时间" prop="effectiveTimeList">
        <el-date-picker
          v-model="itemData.effectiveTimeList"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>-->

      <!-- <el-form-item label="参数依赖" v-if="itemData.parameterType != 'BOT'">
        <div class="absolute" style="z-index: 97" v-if="dependencyList.length">
          <chooseTree
            :treeList="dependencyList"
            :defaultProps="{children: 'children', label: 'title'}"
            :nodeKey="'key'"
            @getResult="getDependency"
            :initId="itemData.dependency"
          ></chooseTree>
        </div>
      </el-form-item>-->
    </template>

    <template v-else>
      <!-- <el-form-item label="运算符" v-if="operaterList">
        <ul class="operatorBox flex">
          <li v-for="item in operaterList" :key="item + 'maps131'" draggable @dragstart="drag($event, item)">
            <el-tag type="danger">
              {{ item }}
            </el-tag>
          </li>
        </ul>
      </el-form-item>-->
      <el-form-item label="是否为效率清单项" prop="isEfficiencyItem">
        <el-radio-group v-model="itemData.isEfficiencyItem">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="itemData.isEfficiencyItem" label="属性" prop="attr">
        <el-input v-model="itemData.attr"></el-input>
      </el-form-item>
      <el-form-item label="公式" prop="calculator">
        <calculatorTag :calculatorList.sync="calculatorList" :dependencyList.sync="dependencyList" :chooseVariable.sync="chooseVariable" :propsInfo="{label: 'title'}" ref="calculatorTag"></calculatorTag>
        <!-- <div class="calculator flex">
          <div class="contenteditableBox" @dragover="allowDrop($event)" @drop="drop($event)">
            <el-input type="textarea" :rows="13" v-model="itemData.calculatorText" resize="none"></el-input>
          </div>
          <div class="calculatorTreeBox">
            <el-tree :data="dependencyList" :props="{label: 'title'}" :default-expand-all="true">
              <div
                slot-scope="{ node, data }"
                style="positon: absolute; z-index: 9999;"
                :draggable="(data.isLeaf) ? true : false"
                @dragstart="drag($event, data)"
              >
                <span v-if="!data.isLeaf">{{ node.label }}</span>
                <el-tag v-else>{{ node.label }}</el-tag>
              </div>
            </el-tree>
          </div>
        </div> -->
      </el-form-item>
    </template>
  </el-form>
</template>

<script>
import selectMember from '@/components/selectMember'
import parameterTypeModule from './type.vue'
import chooseTree from '@/components/chooseTree/chooseTree.vue'
import { listRole } from '@/api/system/role'
import checkFormula from '@/utils/checkFormula'
import timeGeter from '@/utils/timeTrans'
import calculatorTag from '@/components/calculatorTag'
export default {
  props: {
    formData: {
      type: Object,
    },
    formIndex: {
      type: Number,
    },
    id: {
      type: String,
    },
  },
  components: { parameterTypeModule, chooseTree, calculatorTag, selectMember },
  watch: {
    selectMemberList: {
      deep: true,
      handler (value) {
        if (value.length) {
          this.selectMemberName = value[0].name
          this.itemData.parameterValueMaintainer = value[0].id
          this.openSelectMember = false
        } else {
          this.selectMemberName = ''
          this.itemData.parameterValueMaintainer = ''
        }
      }
    }
  },
  data() {
    return {
      openSelectMember: false,
      userProps: {children: 'children', label: 'username'},
      roleProps: {children: 'children', label: 'roleName'},
      parameterTypeList: [
        { name: '基础参数', value: 'BASE' },
        // {name: "系统参数", value: "BOT"},
        { name: '组合参数', value: 'ASSEMBLE' },
      ],
      parameterValueFromList: null,
      rules: {
        folderId: [
          { required: true, message: '请选择所属类别', trigger: 'blur' },
        ],
        parameterName: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
        attr: [
          { required: true, message: '请选择输入属性', trigger: 'blur' }
        ],
        parameterValueFrom: [
          { required: true, message: '请选择数据来源', trigger: 'blur' },
        ],
        parameterValue: [
          { required: true, message: '请输入参数值', trigger: 'blur' },
        ],
        effectiveTimeList: [
          { required: true, message: '请选择数据有效期', trigger: 'blur' },
        ],
      },
      rules2: {
        folderId: [
          { required: true, message: '请选择所属类别', trigger: 'blur' },
        ],
        parameterName: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
        calculator: [
          { required: false, message: '请输入公式', trigger: 'change' },
        ],
      },
      dependencyList: [],
      personList: [],
      roleList: [],
      loading: false,
      dateRange: [],
      queryParams: {
        pn: 1,
        ps: 999,
      },
      chooseVariable: null,
      categoryList: [],
      itemData: null,
      // calcHtml: ``,
      calcHtmlList: [],
      operaterList: null,
      botTreeList: [
        {
          children: [],
          isLeaf: 0,
          key: '969396777',
          title: '系统参数',
        },
      ],
      calculatorList: [{type: false}],
      selectMemberList: [],
      selectMemberName: ''
    }
  },
  async created() {
    this.operaterList = window.operaterList
    this.itemData = this.formData.id
      ? JSON.parse(JSON.stringify(this.formData))
      : this.formData

    this.selectMemberName = this.itemData.parameterValueMaintainerName
    if (this.itemData.parameterValueMaintainer) {
      this.selectMemberList.push({id: this.itemData.parameterValueMaintainer, name: this.itemData.parameterValueMaintainerName})
    }

    await this.getCategoryList()
    await this.getBotParam()
    await this.getDependencyList()
    if (this.formData.parameterType != 'ASSEMBLE') {
      await this.getParameterValueFrom()
      await this.queryUser()
      this.getRoleList()
    }

    if (this.itemData && this.itemData.calculator) {
      let calcList = this.itemData.calculator.trim().split(' ')
      let calcListText = this.itemData.calculatorText.trim().split(' ')
      let tempList = []
      calcList.forEach((item, index) => {
        const temp = {}
        temp['key'] = item
        temp['title'] = calcListText[index]
        tempList.push({type: true, data: temp})
        tempList.push({type: false})
      })
      this.calculatorList = this.calculatorList.concat(tempList)
    }
  },
  methods: {
    getSelectMemberList (list) {
      console.log(list)
    },
    handleClose(index) {
      this.calculatorList.splice(index, 2);
    },
    /* 获取参数详情 */
    getParameterInfo () {
      return new Promise((resolve) => {
        this.$params
          .queryDictionaryDetail(this.formData.id)
          .then((res) => {
            if (res.code == 200) {
              // let temp = []
              if ( !res.data.argumentsText || !res.data.argumentsText.length) {
                resolve()
                return
              }

              // res.data.arguments.forEach((item, index) => {
              //   let tempObj = {
              //     key: item,
              //     title: res.data.argumentsText[index]
              //   }
              //   temp.push(tempObj)
              // })

              // temp.forEach(it => {
              //   let index = this.calcHtmlList.findIndex(
              //     (item) => item.title.length >= it.title.length
              //   )
              //   if (index > -1) {
              //     this.calcHtmlList.splice(index, 0, it)
              //   } else {
              //     this.calcHtmlList.push(it)
              //   }
              // })
              
              // console.log(this.calcHtmlList)
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    // drag(ev, info) {
    //   this.chooseVariable = info
    // },
    // /* 元素放置 */
    // allowDrop(ev) {
    //   ev.preventDefault()
    // },
    // drop(ev) {
    //   ev.preventDefault()

    //   this.itemData.calculatorText += ` ${this.chooseVariable.title} `
    //   let index = this.calcHtmlList.findIndex(
    //     (item) => item.title.length >= this.chooseVariable.title.length
    //   )
    //   if (index > -1) {
    //     this.calcHtmlList.splice(index, 0, this.chooseVariable)
    //   } else {
    //     this.calcHtmlList.push(this.chooseVariable)
    //   }
    //   console.log(this.calcHtmlList)
    // },
    /* 获取参数类型 */
    getParameterType() {
      return new Promise((resolve) => {
        this.$params
          .getParameterType()
          .then((res) => {
            if (res.code == 200) {
              this.parameterTypeList = res.data
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.pageLoading = false
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 获取数据来源 */
    getParameterValueFrom() {
      return new Promise((resolve) => {
        this.$params
          .getParameterValueFrom()
          .then((res) => {
            if (res.code == 200) {
              this.parameterValueFromList = res.data.splice(0, 2)
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.pageLoading = false
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 改变参数类型 */
    changeParameterValueFrom(para) {
      // console.log(para)
      this.itemData.parameterValueMaintainer = ''
      this.selectMemberName = ''
    },
    getBotParam() {
      return new Promise((resolve) => {
        this.$params
          .queryDictionaryAsList({ pn: 1, ps: 9999, parameterType: 'BOT' })
          .then((res) => {
            if (res.code == 200) {
              res.data.rows.forEach((item) => {
                let temp = {
                  children: [],
                  isLeaf: 1,
                  key: item.parameterCode,
                  title: item.parameterName,
                }
                this.botTreeList[0].children.push(temp)
              })
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 获取参数依赖列表 */
    getDependencyList() {
      return new Promise((resolve) => {
        this.$params
          .queryDictionaryAsTreeWithoutComb({
            // folderId: this.id
          })
          .then((res) => {
            if (res.code == 200) {
              this.dependencyList = this.botTreeList.concat(res.data) //合并数组
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.pageLoading = false
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 提交过滤 */
    submitItem() {
      this.itemData.folderId || (this.itemData.folderId = this.id)
      console.log(this.$refs.calculatorTag)
      if (this.$refs.calculatorTag && !this.$refs.calculatorTag.calculator) {
        this.$message.error("请创建公式后提交!")
        return
      }
      return new Promise((resolve, reject) => {
        this.$refs['formData' + this.formIndex].validate((valid) => {
          delete this.itemData.effectiveTimeList

          if (valid) {
            let params = {}
            let httpApi = ''
            if (this.itemData.id) {
              httpApi = 'editDictionary'
              params.params = this.itemData
              params.id = this.itemData.id
              params.params.argumentsText = null
            } else {
              httpApi = 'addDictionary'
              params.params = this.itemData
            }

            // let newList = JSON.parse(JSON.stringify(this.calcHtmlList))
            // params.params.calculator = checkFormula.transformKey(
            //   params.params.calculatorText,
            //   newList.reverse()
            // )
            if (this.$refs.calculatorTag) {
              params.params.calculator = this.$refs.calculatorTag.calculator
              params.params.calculatorText = this.$refs.calculatorTag.calculatorText
            }

            console.log(params)

            this.$params[httpApi](params)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success('提交成功!')
                  resolve(true)
                } else {
                  resolve(this.formIndex)
                  this.$message.error(res.code + '-' + res.msg)
                }
              })
              .catch((err) => {
                resolve(this.formIndex)
                this.$message.error(JSON.stringify(err))
              })
          } else {
            resolve(this.formIndex)
            return false
          }
        })
      })
    },
    /* 查询用户 */
    queryUser() {
      this.loading = true
      return new Promise((resolve) => {
        this.$report
          .userList()
          .then((res) => {
            if (res.code === 200) {
              // let hasEmailArr = res.data.filter(item => (item.email != null && item.email))
              this.personList = res.data.rows
              resolve()
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.loading = false
          })
          .catch((e) => {
            this.$message.error(e.toString())
          })
      })
    },
    /* 赋值 */
    getUserId(item) {
      this.itemData.parameterValueMaintainer = item.id
    },
    getRoleId(item) {
      this.itemData.parameterValueMaintainer = item.id
    },
    getDependency(item) {
      this.itemData.dependency = item.key
    },
    getFolderId(item) {
      this.itemData.folderId = item.key
    },
    getRoleList() {
      listRole(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.roleList = response.data.rows
        }
      )
    },
    getCategoryList() {
      return new Promise((resolve) => {
        this.$params
          .queryParemtFld()
          .then((res) => {
            if (res.code === 200) {
              // let hasEmailArr = res.data.filter(item => (item.email != null && item.email))
              this.categoryList = res.data
              resolve()
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.loading = false
          })
          .catch((e) => {
            this.$message.error(e.toString())
          })
      })
    },
    // keyToId (list) {
    //   for(let item of list) {
    //     item['id'] = item.key
    //     if (item.children && item.children.length) {
    //       item.children = this.keyToId(item.children)
    //     }
    //   }
    //   return list
    // }
  },
}
</script>

<style lang='less'>
.el-collapse-item__wrap {
  overflow: visible;
}
.selectInput{
  height: 36px;
  line-height: 36px;
  width: 260px;
  border: 1px solid #DCDFE6;
  box-sizing: border-box;
  text-indent: 10px;
  border-radius: 4px;
}
.selectBox{
  margin-top: 10px;
  background-color: white;
  border: 1px solid #DCDFE6;
  box-sizing: border-box;
  padding: 20px;
  border-radius: 4px;
}
.calculator {
  width: 100%;
  height: 300px;
}
.contenteditableBox {
  width: 65%;
  height: 100%;
  // padding: 10px;
  // box-sizing: border-box;
  // border: 1px solid #DCDFE6;
  border-radius: 4px;
  white-space: pre-wrap;
}
.calculatorTreeBox {
  width: 35%;
  height: 330px;
  padding: 0 0 0 20px;
  box-sizing: border-box;
  overflow: auto;
}
.tagBox {
  background-color: #ecf5ff;
  display: inline-block;
  height: 32px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 12px;
  color: #409eff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}
.tagBoxRed {
  display: inline-block;
  height: 32px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 12px;
  border: 1px solid #d9ecff;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
  background-color: #ffeded;
  border-color: #ffdbdb;
  color: #ff4949;
}
.operatorBox {
  margin: 0;
  padding: 0;
  overflow: auto;
  li {
    list-style: none;
    margin-right: 10px;
    font-size: 16px;
  }
}
</style>
